<?php
// +----------------------------------------------------------------------
// | AI享乐学 [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author:
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\common\controller\Common;
use app\admin\model\AuthRule;
use think\Db;
use think\Cache;
use think\Imgcompress;
use think\Session;

class Base extends Common{

    protected $api_user = 'user'; //用户表
    protected $api_user_region = 'user_region'; //用户区域表
    protected $api_user_integral = 'user_integral'; //用户积分明细表
    protected $api_user_withdrawal_record = 'user_withdrawal_record'; //用户提现明细表
    protected $api_supervisor = 'supervisor'; //监督员表
    protected $api_goods = 'goods'; //商品表
    protected $api_goods_middle = 'goods_middle'; //商品中间表
    protected $api_goods_order = 'goods_order'; //商品订单表


    public $user;
    public $pageNum;
    public $pernumber;
    public function __construct(){
        $this->pageNum = 1;// 默认页码
        $this->pernumber = 6;// 默认分页参数
    }


    //json中文处理
    function encodeJson($json){
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',function ($matches){
            return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");
        },$json);
    }


    //返回消息
    public function alertMsg($code,$msg,$data=array()){
        $jsonarr = array(
            'code' => (string)$code,
            'msg'  => (string)$msg,
            'data' => $data,
        );
        echo $this->encodeJson(json_encode($jsonarr));
        exit();
    }


    /**
     * print_r打印
     * @param $data         //打印的参数
     */
    public function pre($data){
        echo '<pre>';
        print_r($data);
        echo '<pre>';
    }


    // 用户接口验证
    protected function sign(){
        // $sign = input('sign');
        // if (empty($sign)) {
        //  exit(JsonP(array('code' => -1, 'msg' => '无效签名',)));
        // }
        // if ($sign != config('sign')) {
        //  exit(JsonP(array('code' => -1, 'msg' => '签名错误',)));
        // }

        // 用户登录验证
        $id = input('member_id', 0, 'intval');
        $user = Db::name($this->table_member)->where('member_id', $id)->find();
        if (empty($user)) {
            $this->alertMsg(10, '请先登录');
        }
        $this->user = $user;
        return $user;
    }


    /**
     * 获取用户openid
     */
    public function getOpenid(){
        header("Content-type: text/html; charset=utf-8");
        if(!isset($_GET['code'])){
            $APPID='wxd8ce84192461a3fc';
            $REDIRECT_URI='https://xbl.yugonghuanjing.com/api/Login/getOpenid';
            $scope='snsapi_base';
//            $scope='snsapi_userinfo';//获取用户信息时开启
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state=wx'.'#wechat_redirect';
            header("Location:".$url);
        }else{
            $appid = "wxd8ce84192461a3fc";
            $secret = "d7eac74151b2575622385192a953e75a";
            $code = $_GET["code"];
            $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$get_token_url);
            curl_setopt($ch,CURLOPT_HEADER,0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
            $res = curl_exec($ch);
            curl_close($ch);
            $json_obj = json_decode($res,true);
            $openid = $json_obj['openid'];

            $home_url = Session::get('home_url');
            Session::delete('home_url');
            $this->redirect($home_url,array('openid'=>$openid));
            //根据openid和access_token查询用户信息（待定）
//            $access_token = $json_obj['access_token'];
//            $openid = $json_obj['openid'];
//            $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//
//            $ch = curl_init();
//            curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
//            curl_setopt($ch,CURLOPT_HEADER,0);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
//            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//            $res = curl_exec($ch);
//            curl_close($ch);

            //解析json
//            $user_obj = json_decode($res,true);
//            $_SESSION['user'] = $user_obj;
        }
        die;
    }


    /**
     * 获取区域id组
     * @param $ids              //id组
     * @return string
     * @throws \think\exception\DbException
     */
    protected function apiUserRegion($ids){
        $region_list = Db::name($this->api_user_region)->whereIn('id',$ids)->field('name')->select();
        return $this->splicingAddress($region_list);
    }


    /**
     * 拼接区域地址
     * @param $list             //数据列表
     * @return string
     */
    protected function splicingAddress($list){
        $_region = '';
        if ($list){
            foreach ($list as $val) {
                $val = join('',$val);
                $_region .= $val;
            }
        }
        return $_region;
    }


    /**
     * 寻找所有父级元素
     * @param $id                   //查询的id
     * @param $ancestor
     * @return array
     */
    protected function apiParent($id, $ancestor){
        static $parent=array();
        foreach($ancestor as $v){
            //从小到大 排列
            if($v["id"]==$id){
                $parent[]=$v;
                if($v["pid"] > 0){
                    $this->apiParent($v["pid"],$ancestor);
                }
            }
        }
        $columnlist = array_column($parent,'lv');//重新排序
        array_multisort($columnlist,SORT_ASC,$parent);
        return $parent;
    }


    /**
     * 获取用户二维码
     * @param $openid               //openid
     * @param $uid                  //用户id
     * @return string
     */
    protected function apiQrCode($openid,$uid){
        //二维码
        vendor('phpqrcode/phpqrcode');//引入类库
        $value = 'https://xbl.yugonghuanjing.com/home/Login/scan_qrcode?uid='.$uid;
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 10;//生成图片大小（1-10）
        //生成二维码图片
        $new_file = ROOT_PATH.'data/upload/user_qr_code/';
        $new_fileTime = $new_file.date('Y-m-d').'/';
        if (!file_exists($new_file)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0777, true);
        }
        if (!file_exists($new_fileTime)) {
            mkdir($new_fileTime, 0777, true);
        }
        $filename = time() . '_' .$openid. '.png'; //文件名
        //生成二维码
        $qRcode = new \Qrcode();
        $qRcode::png($value,$new_fileTime.$filename,$errorCorrectionLevel,$matrixPointSize,2);
        //如果需要转换成base64数据，解开下面这行注释即可
        //$image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
        //获取当前域名 $request = Request::instance(); $domain = $request->domain();
        return 'data/upload/user_qr_code/'.date('Y-m-d').'/'.$filename;
    }


    /**
     * 生成二维码（公共方法）
     * @param $url                   //二维码访问路径
     * @param $path                  //文件储存路径
     * @return string
     */
    protected function createQrCode($url,$path){
        //二维码
        vendor('phpqrcode/phpqrcode');//引入类库
        $errorCorrectionLevel = 'L';//容错级别
        $matrixPointSize = 10;//生成图片大小（1-10）
        //生成二维码图片
        $new_file = ROOT_PATH.$path;
        $new_fileTime = $new_file.date('Y-m-d').'/';
        if (!file_exists($new_file)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0777, true);
        }
        if (!file_exists($new_fileTime)) {
            mkdir($new_fileTime, 0777, true);
        }
        $filename = time() . '_' .uniqid(). '.png'; //文件名
        //生成二维码
        $qRcode = new \Qrcode();
        $qRcode::png($url,$new_fileTime.$filename,$errorCorrectionLevel,$matrixPointSize,2);
        //如果需要转换成base64数据，解开下面这行注释即可
        //$image_data = chunk_split(base64_encode(fread(fopen($filename, 'r'), filesize($filename))));
        //获取当前域名 $request = Request::instance(); $domain = $request->domain();
        return $path.date('Y-m-d').'/'.$filename;
    }


    /**
     * 正常上传
     * @param $param            //请求数据
     * @return array
     */
    public function getFiles($param){
        $image_suffix  = explode('.', $param['file']['name']); //得到图片的后缀
        $image_suffixs =  $image_suffix[count($image_suffix)-1];
        $image_name = $image_suffix[0]; //得到图片命名
        if ($param['type'] == 'img') {
            $array = ['png', 'jpg', 'jpeg'];
            $msg = '格式错误，请上传png,jpg,jpeg文件！';
            $size = 3;
        }elseif ($param['type'] == 'file'){
            $array = ['pdf','doc','docx','xls','xlsx'];
            $msg = '格式错误，请上传pdf,doc,docx,xls,xlsx文件！';
            $size = 30;
        }elseif ($param['type'] == 'video') {
            $array = ['mp4','avi'];
            $msg = '格式错误，请上传mp4,avi文件！';
            $size = 50;
        }elseif ($param['type'] == 'mp3') {
            $array = ['mp3','cd','ogg','asf','wma','wav','real','ape','module','midi','vqf'];
            $msg = '格式错误，请上传mp3文件！';
            $size = 10;
        }
        if (!in_array($image_suffixs,$array)) {
            return ['code' => 300,'msg' => $msg];
        }
        if ($param['file']['size'] > 1024000 * $size) {
            return ['code' => 300,'msg' => '文件大小请勿超过'.$size.'兆！'];
        }
        $new_file = ROOT_PATH.$param['path'];
        $new_fileTime = $new_file.date('Y-m-d').'/';
        if (!file_exists($new_file)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0755, true);
        }
        if (!file_exists($new_fileTime)) {
            mkdir($new_fileTime, 0755, true);
        }
        $upload_path = time() . '_' . uniqid() . '.'.$image_suffixs; //文件名
        if ($param['file']['name'] != "" && $param['file']['error'] == UPLOAD_ERR_OK) {
            $move = move_uploaded_file($param['file']['tmp_name'], $new_fileTime.$upload_path);
            if ($move == true) {
                return ['code'=>200,'url' => $param['path'].date('Y-m-d').'/'.$upload_path];
            } else {
                return ['code'=>300,'msg'=>"文件上传失败，请联系管理员检查目录文件夹是否具有可写权限！"];
            }
        } else {
            return ['code'=>300,'msg'=>"文件上传失败，请重试！"];
        }
    }
}